# -*- coding: utf-8 -*-

from PyQt4.QtGui import QImage, QPixmap
from PyQt4.QtCore import *
from PyQt4.QtNetwork import QHttp

class ImageLoader(QObject):

	connection = None
	track = None
	buffer = None

	def __init__(self, track):

		QObject.__init__(self)
		self.track = track

	def load(self):

		if self.track.art == None:

			return

		url = QUrl(self.track.art)
		if url.isValid():

			self.buffer = QBuffer()
			self.connection = QHttp(url.host())

			#print url.host()

			self.connect(self.connection, SIGNAL('requestFinished(int, bool)'), self.processImage)
			self.connection.get(QString(url.encodedPath()), self.buffer)
			#self.connection.get('/', self.buffer)

			#print QString(url.encodedPath())
		#else:
		
			#print 'url not valid:', self.track.art


	def processImage(self, id, error):

		if error:
			
			return

			#print 'error loading', self.track.art
			#print self.connection.errorString()
		else:

			#print self.track.art,'loaded.'

			pixmap = QPixmap()
			pixmap.loadFromData(self.buffer.data())
			self.track.pixmap = pixmap

			self.emit(SIGNAL('success()'))

